<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import type { BasicOption } from '@vben/types';

import { computed, markRaw, ref } from 'vue';

import { AuthenticationLogin, ImageCaptcha, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useAuthStore } from '#/store';
import { captcha, getCaptchaOpenFlag } from '#/api/core';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();
const captchaFlag = ref(true);
const refreshCaptcha = ref(false);

// 判断是否启用图验证码
getCaptchaOpenFlag().then((res: any) => {
  captchaFlag.value = res.flag;
});


const formSchema = computed((): VbenFormSchema[] => {
  // 公共字段
  const commonFields = [
    {
      component: 'VbenInput',
      defaultValue: '',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
      },
      fieldName: 'user_name',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
      formItemClass: 'col-span-12',
    },
    {
      component: 'VbenInputPassword',
      defaultValue: '',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
      formItemClass: 'col-span-12',
    },
  ];

  // 根据 captchaFlag 添加验证码相关字段
  if (captchaFlag.value) {
    return [
      ...commonFields,
      {
        component: 'VbenInput',
        defaultValue: '',
        componentProps: {
          placeholder: '请输入图片验证码',
        },
        formItemClass: 'col-span-8',
        fieldName: 'code',
        label: '验证码',
        rules: z.string().min(1, { message: '请输入图片验证码' }),
      },
      {
        component: markRaw(ImageCaptcha),
        fieldName: 'uuid',
        componentProps: {
          api: captcha,
          uuidField: 'uuid',
          base64Field: 'base64',
          refresh: refreshCaptcha,
          'onUpdate:refresh': () => {
            refreshCaptcha.value = false;
          },
        },
        formItemClass: 'col-span-4',
      },
    ];
  }

  return commonFields;
});


const handleSubmit = (data: any) => {
  authStore.authLogin(data).catch(() => {
    refreshCaptcha.value = true;
  });
};

</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    :show-code-login="true"
    :show-forget-password="false"
    :show-qrcode-login="true"
    :show-register="false"
    :show-remember-me="false"
    :show-third-party-login="false"
    @submit="handleSubmit"
  />
</template>
